"""
@filename: user.py
@project: flask_project
@author: wlf
@time: 2022-09-07
"""
from wtforms import Form, StringField
from wtforms.validators import DataRequired, Regexp, ValidationError
from model.user import UserManager
from werkzeug.security import check_password_hash


class UserForm(Form):
    # 对客户端传递过来的username，school, admission_date, password, cellphone进行修改
    # 变量名需要和客户端传递的字段名一致
    username = StringField(validators=[DataRequired()])
    school = StringField(validators=[DataRequired()])
    admission_date = StringField(validators=[DataRequired()])
    password = StringField(validators=[DataRequired(), Regexp(r'\w{6,18}', message="密码不符合要求")])
    cellphone = StringField(validators=[DataRequired(), Regexp(r'1\d{10}', message="电话不符合要求")])

    # 自定义验证器，验证手机号码是否唯一
    # 自定义检查字段 方法名：validate_你要检查的字段
    # value  客户端传递过来的cellphone对象
    def validate_cellphone(self, value):
        if UserManager.query.filter_by(cellphone=value.data).first():
            raise ValidationError("手机号已存在")


class LoginForm(Form):
    cellphone = StringField(validators=[DataRequired(), Regexp(r'1\d{10}', message="电话不符合要求")])
    password = StringField(validators=[DataRequired(), Regexp(r'\w{6,18}', message="密码不符合要求")])

    def validate(self):
        # 调用父类去验证输入的cellphone,password是否合法，
        super().validate()
        # 如果上面检测没有通过，self.errors就不为None，就会为真，返回false，验证失败
        if self.errors:
            return False
        user = UserManager.query.filter_by(cellphone=self.cellphone.data).first()
        # 如果用户存在，并且密码验证通过
        if user and check_password_hash(user.password, self.password.data):
            return user
        else:
            raise ValidationError("验证失败！")